﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using AugustaDevelopersGuild.Models;
using PagedList;

namespace AugustaDevelopersGuild.Controllers
{
    public class HomeController : Controller
    {
        IMeetingRepository meetingRepository;

        private const int PageSize = 5;

        public HomeController()
            : this(new MeetingRepository()) {
        }

        public HomeController(IMeetingRepository repository)
        {
            meetingRepository = repository;
        }

        public ActionResult Index(string q, int? page)
        {
            IQueryable<Meeting> meetings = null;

            if (!string.IsNullOrWhiteSpace(q))
                meetings = meetingRepository.FindByText(q).OrderBy(d => d.EventDate);
            else
                meetings = meetingRepository.All.OrderByDescending(x => x.EventDate);

            int pageIndex = page ?? 1;
            return View(meetings.ToPagedList(pageIndex, PageSize));
        }

        public ActionResult About()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SendFeedback(Feedback model)
        {
            if (ModelState.IsValid)
            {
                var message = new MailMessage();
                message.To.Add("contact@augustadevelopers.org");
                message.From = new MailAddress(model.Email);
                message.Sender = message.From;
                message.ReplyToList.Add(message.From);
                message.Subject = "[ADG] Website Contact";
                message.Body = model.Message;

                var smtpMail = new SmtpClient();
                smtpMail.Send(message);

                return Content("Thanks - we appreciate your feedback!", "text/html");
            }
            return Content("Something went wrong", "text/html");
        }
    }
}
